#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <filesystem> //C++17
#include <sstream>
#include <fstream>
#include <memory>
#include <ctime>
#include <unistd.h>
#include "Mutex.hpp"

namespace LogModule
{
    using namespace MutexModule;

    const std::string gsep = "\r\n";

    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };

    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        virtual ~ConsoleLogStrategy() = default;
        virtual void SyncLog(const std::string &message) override
        {
            MutexGuard mg(_mutex);
            std::cout << message << gsep;
        }

    private:
        Mutex _mutex;
    };

    const std::string defaultpath = "./log";
    const std::string defaultfilename = "my.log";
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string &path = defaultpath, const std::string &filename = defaultfilename)
            : _path(path),
              _filename(filename)
        {
            // 访问文件系统也是临界资源，需要加锁
            MutexGuard mg(_mutex);
            if (std::filesystem::exists(path))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << std::endl;
            }
        }

        virtual ~FileLogStrategy() = default;

        virtual void SyncLog(const std::string &message) override
        {
            std::string file = _path + (_path.back() == '/' ? "" : "/") + _filename;
            MutexGuard mg(_mutex);
            std::ofstream out(file, std::ios::app);
            if (!out.is_open())
            {
                return;
            }
            out << message << gsep;
            out.close();
        }

    private:
        std::string _path;
        std::string _filename;
        Mutex _mutex;
    };

    enum class LogLevel
    {
        WARNING,
        DEBUG,
        INFO,
        ERROR,
        FATAL
    };

    std::string LevelToString(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }

    std::string GetTimeStamp()
    {
        time_t cur = time(nullptr);
        struct tm curr_tm;
        localtime_r(&cur, &curr_tm);
        char timebuffer[128];
        snprintf(timebuffer, sizeof(timebuffer), "%04d-%02d-%02d %02d:%02d:%02d",
                 curr_tm.tm_year + 1900,
                 curr_tm.tm_mon + 1,
                 curr_tm.tm_mday,
                 curr_tm.tm_hour,
                 curr_tm.tm_min,
                 curr_tm.tm_sec);
        return timebuffer;
    }

    class Logger
    {
    public:
        void EnableConsoleLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsoleLogStrategy>();
        }

        void EnableFileLogStrategy()
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }
        Logger()
        {
            EnableConsoleLogStrategy();
        }

        // 左半部分
        class LogMessage
        {
        public:
            LogMessage(LogLevel level, const std::string &src, int line, Logger &log)
                : _time(GetTimeStamp()), _level(level), pid(getpid()), _src(src), _line(line), _log(log)
            {
                std::stringstream ss;
                ss << "[" << _time << "]"
                   << "[" << LevelToString(_level) << "]"
                   << "[" << pid << "]"
                   << "[" << _src << "]"
                   << "[" << _line << "]"
                   << "- ";
                _info = ss.str();
            }

            ~LogMessage()
            {
                _log._fflush_strategy->SyncLog(_info);
            }

            //右半部分
            template <class T>
            LogMessage &operator<<(T data)
            {
                std::stringstream ss;
                ss << data;
                _info += ss.str();
                return *this;
            }

        private:
            std::string _time;
            LogLevel _level;
            pid_t pid;
            std::string _src;
            int _line;
            std::string _info;
            Logger &_log;
        };

        // 右半部分重载<<输入
        LogMessage operator()(LogLevel level, const std::string &src, int line)
        {
            return LogMessage(level, src, line, *this);
        }

    private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };
    Logger log;

#define LOG(level) log(level, __FILE__, __LINE__)
#define ENABLE_CONSOLE_LOG_STRATEGY() log.EnableConsoleLogStrategy()
#define ENABLE_FILE_LOG_STRATEGY() log.EnableFileLogStrategy()
};
